package com.ztesoft.zcm.cmdb.util.remote;

import com.google.common.base.Preconditions;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import lombok.Data;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author li.peilong
 * @date 2019/05/22
 **/
@Data
public class PooledRemoteClient extends RemoteClient {
    private RemoteClientHolder holder;
    private RemoteClient remoteClient;
    private final AtomicBoolean closed = new AtomicBoolean();
    public PooledRemoteClient(RemoteClientHolder holder) {
        super(holder.getRemoteClient().getHostAccessInfo());
        this.holder = holder;
        this.holder.setLastActiveTime(System.currentTimeMillis());
        this.remoteClient = holder.getRemoteClient();
    }
    @Override
    public void close() {
        if (!closed.compareAndSet(false, true)) {
            return;
        }
        RemoteClientPool pool = this.holder.getPool();
        pool.recycle(this);
        this.holder = null;
        this.remoteClient = null;
    }

    @Override
    public RemoteResult exec(String cmd, String... patterns) throws BaseAppException {
        Preconditions.checkArgument(!this.closed.get(), "RemoteClient already closed");
        return remoteClient.exec(cmd, patterns);
    }

    @Override
    public RemoteResult exec(String cmd, int timeout, String... patterns) throws BaseAppException {
        Preconditions.checkArgument(!this.closed.get(), "RemoteClient already closed");
        return remoteClient.exec(cmd, timeout, patterns);
    }

    @Override
    public String toString() {
        return "PooledRemoteClient{" +
                "remote host=" + remoteClient.getHostAccessInfo().getHost() +
                '}';
    }
}
